package com.example.myui.activity.service;

import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.example.myui.activity.MultiDownloadActivity;
import com.lzy.okgo.model.Progress;

/**
 * Created by Administrator on 2018/2/2/002.
 */

public class DownloadService extends IntentService {

    private LocalBroadcastManager localBroadcastManager;
    private String TAG = DownloadService.class.getSimpleName();

    public DownloadService() {
        super("DownloadService");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        sendServiceStatus("启动服务");
    }

    private void sendServiceStatus(String status) {
        Intent intent = new Intent(MultiDownloadActivity.ACTION_TYPE_SERVICE);
        intent.putExtra("status", status);
        localBroadcastManager.sendBroadcast(intent);

    }

    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
//        Progress progress = (Progress) intent.getSerializableExtra("progress");
//        Log.i(TAG, "onStartCommand: " + progress.fraction);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Progress progress = (Progress) intent.getSerializableExtra("progress");
        Log.i(TAG, "onHandleIntent: "+ progress.fraction);
        sendThreadStatus(progress.fraction);
    }

    private void sendThreadStatus(float fraction) {
        Intent intent = new Intent(MultiDownloadActivity.ACTION_TYPE_THREAD);
        intent.putExtra("fraction",fraction);
        localBroadcastManager.sendBroadcast(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        sendServiceStatus("服务结束");
    }
}
